package com.mifengs.mall.ui.my.version;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mifengs.commonbase.util.DeviceInfoUtil;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.mall.Constant;
import com.mifengs.mall.MallApplication;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.mall.entity.ResponseInfo;
import com.mifengs.mall.entity.UpdateData;
import com.mifengs.mall.netWork.NetWork;
import com.mifengs.mall.services.DownloadService;
import com.mifengs.mall.widget.CircleRecyclerView.HorizontalProgressBar;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by lynn on 2018/7/16.
 */

public class CurrentVersionActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    @BindView(R.id.rl_quit)
    RelativeLayout rlQuit;
    @BindView(R.id.rLayout_function)
    RelativeLayout rLayoutFunction;
    @BindView(R.id.is_update_img)
    ImageView isUpdateImg;
    @BindView(R.id.tv_current_version)
    TextView tvCurrentVersion;
    @BindView(R.id.rLayout_version_update)
    RelativeLayout rLayoutVersionUpdate;
    private Dialog mAppUpdateDialog;
    private Button okBtn;
    private boolean isPermissions = false;
    private UpdateData mUpdateData;
    private boolean isUpdate = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_current_version);
        ButterKnife.bind(this);
        setStatusColorAndMode(R.color.white,true);
        init();
    }

    private void init() {
        tvCurrentVersion.setText("V_"+ DeviceInfoUtil.getAppVersion(getContext()));
        getUpdateInfo();
    }

    @OnClick({R.id.rl_quit, R.id.rLayout_function,R.id.rLayout_version_update})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_quit:
                finish();
                break;
            case R.id.rLayout_function:
                startActivity(new Intent(getContext(), VersionListfAcitvity.class));
                break;
            case R.id.rLayout_version_update:
                if(isUpdate){
                    showUpdateDialog();
                }else{
                    ToastUitl.show("当前已经是最新的版本了",2000);
                }
                break;
        }
    }

    public void getUpdateInfo() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("platform", "1");
        NetWork.getApplyGoodsApi().getInfo(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseInfo<UpdateData>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(ResponseInfo<UpdateData> updateDataResponseInfo) {
                        if (updateDataResponseInfo.getStatus() == Constant.OK_CODE) {
                            try {
                                mUpdateData = updateDataResponseInfo.getResult();
                                String webVerCode = mUpdateData.getVersion();
                                String nowVerCode = DeviceInfoUtil.getAppVersion(MallApplication.getInstance());
                                if (webVerCode.compareTo(nowVerCode) > 0) {
                                    isUpdateImg.setVisibility(View.VISIBLE);
                                    isUpdate = true;
                                }
                            } catch (Exception e) {

                            }
                        }
                    }
                });
    }


    public void showUpdateDialog() {
        mAppUpdateDialog = new Dialog(this, R.style.dialog);
        mAppUpdateDialog.setContentView(R.layout.dialog_update);
        String oldestVersion = mUpdateData.getOldestVersion();
        String nowVerCode = DeviceInfoUtil.getAppVersion(MallApplication.getInstance());

        if (nowVerCode.compareTo(oldestVersion) >= 0) {
            mAppUpdateDialog.setCanceledOnTouchOutside(true);
            (mAppUpdateDialog.findViewById(R.id.bt_cancle)).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mAppUpdateDialog.dismiss();
                }
            });
        } else {
            mAppUpdateDialog.setCanceledOnTouchOutside(false);
            (mAppUpdateDialog.findViewById(R.id.bt_cancle)).setVisibility(View.GONE);
        }
        TextView tvUpdateInfo = (TextView) mAppUpdateDialog.findViewById(R.id.tv_update_info);
        tvUpdateInfo.setText(mUpdateData.getResRemark());
        okBtn = mAppUpdateDialog.findViewById(R.id.bt_update);
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                needDownLoad();
            }

        });

        mAppUpdateDialog.show();

        mAppUpdateDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == event.KEYCODE_BACK) {
                    finish();
                } else {
                    return false;
                }
                return false;
            }

        });
        HorizontalProgressBar horizontalProgressBar = new HorizontalProgressBar(getContext());
        for (int i = 0; i < 20; i++) {
            horizontalProgressBar.setCurrentProgress(i);
            horizontalProgressBar.setProgressWithAnimation(i);
        }

    }


    @AfterPermissionGranted(REQUEST_PERMISSION_STORAGE)
    public void needDownLoad() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            isPermissions = true;
            String isPermissions = PreferenceUtils.getStringPreference(getContext(), "isPermissions");
            if (Integer.parseInt(isPermissions) == 1) {
                downLoadApp();
            }
            PreferenceUtils.saveStringPreference(getContext(), "isPermissions", "1");
        } else {
            PreferenceUtils.saveStringPreference(getContext(), "isPermissions", "0");
            EasyPermissions.requestPermissions(this, "app需要存储权限",
                    REQUEST_PERMISSION_STORAGE, perms);
        }
    }

    private void downLoadApp() {
        if (mUpdateData != null) {
            if (!TextUtils.isEmpty(mUpdateData.getUrl())) {
                Intent intent = new Intent(this, DownloadService.class);
                intent.putExtra("AppUpdateInfo", mUpdateData.getUrl());
                startService(intent);
                okBtn.setText("下载更新中，请耐心等待...");
            }
            okBtn.setEnabled(false);
        }

//        mAppUpdateDialog.dismiss();
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }

}
